package com.jgy.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jgy.annotation.SetLogValue;
import com.jgy.entity.SpaceUser;
import com.jgy.entity.Systemlog;
import com.jgy.entity.UserRole;
import com.jgy.mapper.SpaceUserMapper;
import com.jgy.mapper.UserRoleMapper;
import com.jgy.utils.CommonConstants;
import com.jgy.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author 姜光远
 * @date 2023/4/1 15:28
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private SpaceUserMapper mapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @SetLogValue(modular = "查询用户",type = CommonConstants.SELECT, describe = "查询用户")
    @GetMapping("/getUserList")
    public R<?> getTrueList(@RequestParam(defaultValue = "1") Integer pageNum,
                            @RequestParam(defaultValue = "10") Integer pageSize,
                            @RequestParam(defaultValue = "") String search) {
        LambdaQueryWrapper<SpaceUser> wrapper = Wrappers.<SpaceUser>lambdaQuery();
        if (StrUtil.isNotBlank(search)) {
        wrapper.like(true,SpaceUser::getUsername, search);
        }
        Page<SpaceUser> userPage = mapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        userPage.setTotal(userPage.getRecords().size());
        return R.ok(userPage);
    }


    @PostMapping
    public R<?> save(@RequestBody SpaceUser user) {

        mapper.insert(user);

        UserRole userRole = UserRole.builder()
                .userId(Integer.parseInt(user.getId()))
                .roleId(2)
                .build();
        userRoleMapper.insert(userRole);

        return R.ok();
    }

    @PutMapping
    public R<?> update(@RequestBody SpaceUser user) {
        mapper.updateById(user);
        return R.ok();
    }
}
